package com.bci.pwtz.controller.admin;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.bci.pwtz.admin.service.AdminSmsSendLogService;
import com.bci.pwtz.common.PwtzConstants;
import com.bci.pwtz.common.util.ExcelUtil;
import com.bci.pwtz.common.util.JsonUtils;
import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.mysql.model.AdminSmsSendLog;
import com.bci.pwtz.service.sms.SendSmsService;

@Controller
@RequestMapping("/admin/sms")
public class AdminSmsController extends AdminAbstractController{
    @Autowired
    SendSmsService service;
    @Autowired
    AdminSmsSendLogService logService;
    
    @RequestMapping(value="/batchsend",method=RequestMethod.POST)
    @ResponseBody
    public Map<String,String> batchsend(String receivers,String content,String imageCode){
    	String imageCodeSession = (String) session.getAttribute("imageCode");
    	Map<String,String> map=null;
    	if (!(StringUtils.isNotBlank(imageCodeSession) && imageCodeSession.equalsIgnoreCase(imageCode)))
        {
    		map = packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_ERROR,
                    "ErrorImageCode", "验证码错误！");
    		return map;
        }
        String result="";
        String [] reciverlist=null;
        if(receivers.length()==11){
            reciverlist=new String[]{receivers};
        }else{
            reciverlist=receivers.split(",");
            List<String> errlist=new ArrayList<String>();
            List<String> list=Arrays.asList(reciverlist);
            for(String str:reciverlist){
                if(!PwtzUtils.isMobile(str)){
                    errlist.add(str);
                }
            }
            if(errlist!=null&&errlist.size()>0){
                list.remove(errlist);
            }
            reciverlist=(String[]) list.toArray();
        }
        try{
            Date date=new Date();
            String createTime=PwtzUtils.date2String(date,"yyyyMMddHHmmss");
            result=service.batchSend(reciverlist, content, null, createTime);
            if("0".equals(result)||"1".equals(result)){
                AdminSmsSendLog obj=new AdminSmsSendLog();
                obj.setContent(content);
                obj.setCreateTime(date);
                StringBuffer strbuffer=new StringBuffer();
                if(reciverlist!=null&&reciverlist.length>0){
                    for(int i=0;i<reciverlist.length;i++){
                        strbuffer.append(reciverlist[i]);
                        if(i>0&&i<reciverlist.length-1){
                            strbuffer.append(",");
                        }
                    }
                }
                obj.setMobile(strbuffer.toString());
                obj.setOperatorId(getUserId());
                logService.add(obj);
                map=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_SUCCESS, ERROR_VALUE_MSG_TYPE_INFO, null, "群发短信成功");
            }else{
                map=packageAjaxReturnMap(ERROR_VALUE_OP_RESULT_FAIL, ERROR_VALUE_MSG_TYPE_INFO, null, "群发短信失败");
            }
        }catch(Exception e){
            handleException(e);
        }
        return map;
    }
    
    @RequestMapping(value="/list",method=RequestMethod.POST)
    @ResponseBody
    public PaginationList<AdminSmsSendLog> list(String begintime,String endtime,String operatorname,String content,int pagesize,int pageno){
        PaginationList<AdminSmsSendLog> plist=null;
        try{
            plist=logService.selectSmsSendLogList(begintime, endtime, operatorname, content, pagesize, pageno);
        }catch(Exception e){
            handleException(e);
        }
        return plist;
    } 
    
    @RequestMapping("/readfile")
    @ResponseBody
    public void readFile(HttpServletRequest request,HttpServletResponse response,MultipartFile userFile)
    {
        List<String[]> errorlist =new ArrayList<String[]>();
        System.out.println("userFile="+userFile);
        String result = "";
//        List<String> errorlist = new ArrayList<String>();
        int totalCount = 0;
        int successCount = 0;
        int eroorCount = 0;
        String msgType = "error";
        String opResult = "1";
        String url = "";
        StringBuffer strbuffer=new StringBuffer();
        String phoneListStr="";
        String savePath = "";
        if(PwtzConstants.THE_SERVER_TYPE==1){
            savePath=request.getSession().getServletContext().getRealPath("/")+"\\upload\\";
        }else{
            savePath=request.getSession().getServletContext().getRealPath("/")+"/upload/";
            savePath = savePath.replaceAll("\\\\", "/");    //本地
        }
//        savePath = savePath.replaceAll("/", "\\\\");    //服务器
        try
        {
            if (_log.isInfoEnabled())
            {
                _log.info("开始上传文件");
            }
            String prefix = "";
            String fileName = "";
            String newFileName = "";

            fileName = userFile.getOriginalFilename();
            prefix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            newFileName = System.currentTimeMillis() + PwtzUtils.getRandomNumber(4)+ prefix;
            url = savePath + newFileName;
            BufferedInputStream in = new BufferedInputStream(userFile.getInputStream());
            File file = new File(savePath);
            if  (!file .exists()  && !file .isDirectory())      
            {       
                file.mkdirs();    
            }
//            System.out.println(url);
            FileOutputStream out = new FileOutputStream(new File(url));
            BufferedOutputStream output = new BufferedOutputStream(out);
            Streams.copy(in, output, true);
            List<String[]> list = null;
            if (prefix.endsWith(".xls") || prefix.endsWith(".xlsx"))
            {
                list = ExcelUtil.readExcel(new File(url));
            }
            
            try
            {
                if (list != null && list.size() > 1)
                {
                    totalCount = list.size();
//                    list = removeDuplicate(list);
                    int syzs =list.size();
                    list.remove(0);
                    System.out.println(list);
                    for(String[] str:list){
                        if(str.length>3){
                            if(str[1]!=""&&str[2]!=""&&str[3]!=""&&PwtzUtils.isMobile(str[3])){
                                strbuffer.append(str[3]+",");
                            }else if(!"合计".equals(str[0])){
                                String [] newStr = new String[4];
                                newStr[0]= str[1];
                                newStr[1]= str[2];
                                newStr[2]= str[3];
                                newStr[3]= "输入公司名、用户名或电话号码有错";
                                errorlist.add(newStr);
                            }
                        }else{
                            String [] newStr = new String[4];
                            if(str.length>0)
                            newStr[0]= str[0];
                            if(str.length>1)
                            newStr[1]= str[1];
                            newStr[3]= "输入不完整";
                            errorlist.add(newStr);
                        }
                    }
                    phoneListStr=strbuffer.substring(0, strbuffer.lastIndexOf(","));
                    if (errorlist != null && errorlist.size() > 0)
                    {
                        eroorCount = errorlist.size();
                    }
                    if (list != null && list.size() > 0)
                    {
                        successCount = syzs - eroorCount;
                    }
                }
            }
            catch (Exception e)
            {
                _log.error(ExceptionUtils.getStackTrace(e));
            }
            if (totalCount > 0 && successCount > 0)
            {
                result = "批量入库成功!";
                msgType = "info";
                opResult = "0";
            }
            else if (totalCount == 0)
            {
                result = "批量入库失败,号码文件为空!";
                msgType = "info";
                opResult = "1";
            }
            else if (totalCount > 0 && successCount == 0)
            {
                result = "批量入库失败,文件号码无效!";
                msgType = "info";
                opResult = "2";
            }

            if (_log.isInfoEnabled())
            {
                _log.info(result);
            }
        }
        catch (IOException e)
        {
            result = "文件上传IO异常";
            _log.error(ExceptionUtils.getStackTrace(e));
        }
        catch (Exception e)
        {
            result = "未知异常";
            _log.error(ExceptionUtils.getStackTrace(e));
        }
//        return errorlist;
        System.out.println(JsonUtils.bean2json(errorlist));
        System.out.println(strbuffer.toString());
        writeJsonObject(
                request,
                response,
                "{msgDesc:\"" + result + "\",msgType:\"" + msgType + "\",opResult:\"" + opResult
                        + "\",errorlist:" + JsonUtils.bean2json(errorlist) + ",successCount:\"" + successCount
                        + "\",eroorCount:\"" + eroorCount + "\",totalCount:\"" + totalCount + "\",addr:\""
                        + url.replaceAll("\\\\", "/") +"\",smsStr:\""+phoneListStr+ "\"}");
    }
    
    private void writeJsonObject(HttpServletRequest request, HttpServletResponse resp, String jsonData)
    {
        System.out.println("jsonData="+jsonData);
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter pw = null;
        try
        {
            pw = resp.getWriter();
            pw.print(jsonData);
            pw.flush();
        }
        catch (IOException e)
        {
            handleException(e);
        }
        finally
        {
            if (null != pw)
            {
                pw.close();
            }
        }
    }
}